package com.itfreer.power.service.power.strategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.power.dao.role.RoleDao;
import com.itfreer.power.entity.role.RoleServiceJurisdictionEntity;

/**
 * 应用服务数据获取接口
 * 以角色ID为依据缓存，先从缓存中获取，再从数据库中获取
 */
@Component("MemoryRoleServiceDataProvide")
public class MemoryRoleServiceDataProvide implements RoleServiceDataProvide {

	@Autowired
	private RoleDao roleDao;

	/**
	 * 角色与应用关联缓存
	 */
	private Map<String, List<RoleServiceJurisdictionEntity>> roleServiceCache = 
			new HashMap<String, List<RoleServiceJurisdictionEntity>>();

	@Override
	public List<String> getServiceIDs(List<String> roles) {
		if (roles == null || roles.size() <= 0) {
			return null;
		}
		List<String> result = new ArrayList<String>();
		for (String role : roles) {
			List<RoleServiceJurisdictionEntity> services = null;
			if (roleServiceCache.containsKey(role)) {
				services = roleServiceCache.get(role);
			} else {
				services = roleDao.getServices(role);
				roleServiceCache.put(role, services);
			}
			for (RoleServiceJurisdictionEntity u : services) {
				result.add(u.getFunctionId());
			}
		}
		return result;
	}

	@Override
	public void clearCache(String roleId) {
		if (roleServiceCache.containsKey(roleId)) {
			roleServiceCache.remove(roleId);
		}
	}
}